package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class ApUnlikesBehaviorServiceImpl implements ApUnlikesBehaviorService {

    private final CacheService cacheService;
    /**
     * 不喜欢
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        //1.参数校验
        if (dto == null || checkParams(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.保存数据
        if (dto.getType() == 0){
            //判断是否已经不喜欢
            Object o = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + String.valueOf(dto.getArticleId()), String.valueOf(user.getId()));
            if (o != null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已不喜欢");
            }
            log.info("保存当前key:{} ,{}, {}", dto.getArticleId(), user.getId(), dto);
            cacheService.hPut(BehaviorConstants.UN_LIKE_BEHAVIOR + String.valueOf(dto.getArticleId()), String.valueOf(user.getId()), JSON.toJSONString(dto));
        }else {
            log.info("保存当前key:{} ,{}", dto.getArticleId(), user.getId());
            cacheService.hDelete(BehaviorConstants.UN_LIKE_BEHAVIOR + String.valueOf(dto.getArticleId()), String.valueOf(user.getId()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 参数校验
     * @param dto
     * @return
     */
    private boolean checkParams(UnLikesBehaviorDto dto) {
        return dto.getArticleId() == null || dto.getArticleId() <= 0 || dto.getType() < 0 || dto.getType() > 1;
    }
}
